//
//  UIControl+QTMultiClick.m
//  QTCategory
//
//  Created by 张俊博 on 2017/1/14.
//  Copyright © 2017年 CISDI. All rights reserved.
//

#import "UIControl+QTMultiClick.h"
#import <objc/runtime.h>

static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";
static const char *UIControl_acceptEventTime = "UIControl_acceptEventTime";
static const char *UIControl_disableMutiClick = "UIControl_disableMutiClick";

@interface UIControl ()

@property (nonatomic, assign) NSTimeInterval qt_acceptEventInterval; // 重复点击的间隔

@property (nonatomic, assign) NSTimeInterval qt_acceptEventTime;

@end

@implementation UIControl (QTMultiClick)

+ (void)load {
//    Method before   = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
//    Method after    = class_getInstanceMethod(self, @selector(qt_sendAction:to:forEvent:));
//    method_exchangeImplementations(before, after);
}

- (void)qt_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
//    if (!self.qt_disableMutiClick) {
//        [self qt_sendAction:action to:target forEvent:event];
//        return;
//    }
    
    if ([NSDate date].timeIntervalSince1970 - self.qt_acceptEventTime < self.qt_acceptEventInterval) {
        return;
    }
    
    if (self.qt_acceptEventInterval > 0) {
        self.qt_acceptEventTime = [NSDate date].timeIntervalSince1970;
    }
    
    [self qt_sendAction:action to:target forEvent:event];
    
}

- (NSTimeInterval)qt_acceptEventInterval {
    return  [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
}

- (void)setQt_acceptEventInterval:(NSTimeInterval)qt_acceptEventInterval {
    objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(qt_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval)qt_acceptEventTime {
    return  [objc_getAssociatedObject(self, UIControl_acceptEventTime) doubleValue];
}

- (void)setQt_acceptEventTime:(NSTimeInterval)qt_acceptEventTime {
    objc_setAssociatedObject(self, UIControl_acceptEventTime, @(qt_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)qt_disableMutiClick {
    return [objc_getAssociatedObject(self, UIControl_disableMutiClick) boolValue];
}

- (void)setQt_disableMutiClick:(BOOL)qt_disableMutiClick {
    objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(qt_disableMutiClick), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
